package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;


    @Override
    public R setDefault(AddressBook addressBook) {

        //1、还原所有的默认地址设置 update address_book set is_default = 0 where  user_id =  ?
        LambdaUpdateWrapper<AddressBook> uw = new LambdaUpdateWrapper<>();
        uw.set(AddressBook::getIsDefault,0);// set is_default = 0
        uw.eq(AddressBook::getUserId, UserHolder.getUserId()); // where  user_id =  ?
        addressBookMapper.update(null,uw);

        //2、设置新的默认地址 update address_book set is_default =1 where id = ?
        addressBook.setIsDefault(1);
        int i = addressBookMapper.updateById(addressBook);


        return i>0?R.success("设置默认地址成功"):R.error("设置默认地址失败");
    }
}
